<?php

namespace App\Models;

use App\Models\CollOption;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class CompanyJob extends Model
{
    //表名
    protected $table = 'company_job';

    protected $guarded = [];

    public $timestamps = false;

    /**
     * The attributes that should be hidden for arrays.
     * 隐藏字段
     * @var array
     */
    protected $hidden = ['company_department', 'urgent'];

    /**
     * 要触发的所有关联关系(子类增删改更新父类updatetime)
     *
     * @var array
     */
//    protected $touches = ['company_basic'];
    protected $casts = [
        'id' => 'string', 'salary_above' => 'string',
        'salary_below' => 'string', 'job_status' => 'string',
        'part_status' => 'string', 'gender' => 'string',
        'recruiting_num' => 'string',
    ];

    /**
     * 获取职位对应的用户
     */
    public function company_user()
    {
        return $this->belongsTo(CompanyUser::class, 'uid', 'uid')
            ->select(['uid', 'last_login_time', 'viptime']);
    }

    /**
     * 获取职位对应的公司信息
     */
    public function company_basic()
    {
        return $this->belongsTo(CompanyBasic::class, 'com_id')
            ->select(['id', 'company_name', 'logo']);
    }

    /**
     * 获取职位对应的收藏简历
     */
    public function resume_favorite()
    {
        return $this->hasMany(ResumeFavorite::class, 'job_id')->has('resume')->with('resume')
            ->where('status', '0')->orderBy('updated_at', 'desc');
    }

    /**
     * 职位对应的联系方式
     */
    public function contact()
    {
        return $this->hasOne(CompanyContact::class, 'job_id');
    }

    /**
     * 职位的公司部门
     */
    public function company_department()
    {
        return $this->hasOne(CompanyDepartment::class, 'id', 'department')
            ->select('id', 'name');
    }

    /** 职位的邀请记录
     * @return mixed
     */
    public function interview()
    {
        return $this->hasMany(Interview::class, 'job_id')
            ->select('id', 'job_id', 'resume_id', 'updated_at', 'interview_time',
                'remark', 'status')->with('resume')
            ->whereBetween('status', [0, 3])->orderBy('updated_at', 'desc');
    }

    public function browse_job()
    {
        return $this->hasMany(BrowseJob::class, 'job_id')
            ->has('resume')->with('resume')->orderBy('updated_at', 'desc')
            ->select('id', 'resume_id', 'job_id', 'updated_at');
    }

    /**
     * 获取行业名
     *
     * @return string
     */
    public function getIndustryNameAttribute()
    {
        return CollOption::getOptionName($this->attributes['industry'], 'industry');
    }

    /**
     * 获取职位id数组
     *
     * @return array
     */
    public function getJobCategoryAttribute()
    {
        $arr = [];

        //遍历地区
        for ($i = 1; $i <= 5; $i++) {
            $value = $this['job_category' . $i];
            if ($value != 0) {
                $arr[] = $value;
            }
        }
        return $arr;
    }

    /**
     * 获取职位名
     *
     * @return string
     */
    public function getJobCategoryNameAttribute()
    {
        $temp = implode(',', \DB::table('coll_position')->whereIn('cid', $this['job_category'])->pluck('name'));
        return strlen($temp) < 1 ? '不限' : $temp;
    }

    /**
     * 获取地区id数组
     *
     * @return array
     */
    public function getLocationAttribute()
    {
        $arr = [];

        //遍历地区
        for ($i = 1; $i <= 5; $i++) {
            $value = $this['location' . $i];
            if ($value != 0) {
                $arr[] = $value;
            }
        }
        return $arr;
    }

    /**
     * 获取地区名
     *
     * @return string
     */
    public function getLocationNameAttribute()
    {
        $area = [];
        $town = [];
        foreach ($this->location as $item) {
            if (strlen(strval($item)) > 6) {
                $town[] = $item;
            } else {
                $area[] = $item;
            }
        }
        $areaName = [];
        if (count($area) > 0) {
            $areaName = CollArea::whereIn('cid', $area)->pluck('name', 'cid')->toArray();
        }
        $townName = [];
        if (count($town) > 0) {
            $townName = CollTown::whereIn('cid', $town)->pluck('name', 'cid')->toArray();
        }

        $arr = $areaName + $townName;
        $str = '';
        //遍历地区
        foreach ($this->location as $item) {
            if ($item != 0 && array_key_exists($item, $arr)) {
                $str .= $arr[$item] . ',';
            }
        }

        $temp = rtrim($str, ',');
        return strlen($temp) < 1 ? '地区不限' : $temp;
    }

    /**
     * 获取学历名
     *
     * @return string
     */
    public function getEducationNameAttribute()
    {
        $eduId = $this->attributes['education'];
        if ($eduId == 0) {
            return '学历不限';
        }
        return CollOption::getOptionName($eduId, 'education');
    }

    /**
     * 获取工作经验名
     *
     * @return string
     */
    public function getWorkYearNameAttribute()
    {
        $workId = $this->attributes['work_year'];
        if ($workId == 0) {
            return '经验不限';
        }
        return CollOption::getOptionName($workId, 'work_year');
    }

    /**
     * 获取语言名
     *
     * @return string
     */
    public function getLanguageNameAttribute()
    {
        $langId = $this->attributes['language'];
        if ($langId == 0) {
            return '语言不限';
        }
        return CollOption::getOptionName($langId, 'language');
    }

//    public function getSalaryAboveNameAttribute()
//    {
//        $sId = $this->attributes['salary'];
//        $name = CollOption::getOptionName($sId, 'expectedsalary');
//        return empty($name) ? strval($sId) : $name;
//    }
//
//    public function getSalaryBelowNameAttribute()
//    {
//        $sId = $this->attributes['salary'];
//        $name = CollOption::getOptionName($sId, 'expectedsalary');
//        return empty($name) ? strval($sId) : $name;
//    }

    /**
     * 获取薪资
     *
     * @return string
     */
//    public function getSalaryAttribute()
//    {
//        if ($this['salary_above_name'] == 0 && $this['salary_above_name'] == 0) {
//            return '面议';
//        } elseif ($this['salary_above_name'] == 0) {
//            return $this['salary_below_name'];
//        } elseif ($this['salary_below_name'] == 0) {
//            return $this['salary_above_name'];
//        }
//        return $this['salary_above_name'] . '-' . $this['salary_below_name'];
//    }

    /**
     * 获取年龄要求
     *
     * @return string
     */
    public function getAgeAttribute()
    {
        if ($this['age_above'] == 0 && $this['age_below'] == 0) {
            return '年龄不限';
        } elseif ($this['age_above'] == 0) {
            return $this['age_below'] . '岁以下';
        } elseif ($this['age_below'] == 0) {
            return $this['age_above'] . '岁以上';
        }
        return $this['age_above'] . '-' . $this['age_below'] . '岁';
    }

    /** 部门名称
     * @return mixed
     */
    public function getDepartmentNameAttribute()
    {
        return $this->company_department ? $this->company_department->name : '';
    }

    /** 公司名称
     * @return mixed
     */
    public function getCompanyNameAttribute()
    {
        return $this->company_basic ? $this->company_basic->company_name : '';
    }

    public function getUpdatetimeAttribute($value)
    {
        return Carbon::parse($value)->format('Y-m-d');
    }

    /** 急招
     * @return bool
     */
    public function getIsUrgentAttribute()
    {
        if (is_null($this->urgent) || $this->urgent == '0000-00-00 00:00:00') {
            return 0;
        }
        //当前时间是否小于急招时间+5天
        return intval(Carbon::now()->lt($this->urgent->copy()->addDays(5)));
    }

    public function getJobStatusNameAttribute()
    {
        $status = $this->original['job_status'];
        switch ($status) {
            case 4;
                return '已删除';
                break;

            case 2;
                return '已屏蔽';
                break;

            case 1;
                return ($this->is_urgent == 1 ? '职位加急中' : '审核通过');
                break;

            case 7;
                return '冻结中';
                break;

            default;
                return '正在审核';
                break;
        }
    }

    /** 企业回复率和平均时长
     * @return mixed
     */
    public function getReplyAttribute()
    {
        $send = ResumeSend::where(['company_uid' => $this->uid])
            ->whereBetween('status', [0, 3])//被删除的不算
            ->orderBy('updated_at', 'desc')
            ->get(['status', 'created_at', 'updated_at']);

        $count = $send->count();//总个数
        $total_time = 0;//总时间
        $reply_count = 0;//企业回复个数

        foreach ($send as $item) {
            if ($item->status == 2 || $item->status == 3) {//同意或拒绝
                //时间差,小时为单位
                $total_time += $item->created_at->diffInHours($item->updated_at, true);
                $reply_count += 1;
            }
        }

        if ($count == 0 || $reply_count == 0) {
            $reply['rates'] = 0;//企业回复率
            $reply['average_time'] = '0小时';//企业回复平均时长
        } else {
            $reply['rates'] = round($reply_count / $count, 2) * 100;
            $ave = intval($total_time / $reply_count);//平均小时,
            if ($ave > 24) {//大于24小时转为天数
                $reply['average_time'] = (intval($ave / 24)) . '天';
            } else if ($ave < 1) {//小于1小时
                $reply['average_time'] = '1小时';
            } else {
                $reply['average_time'] = $ave . '小时';
            }
        }

        return $reply;
    }

    public function job_resume_send()
    {
        return $this->hasMany('App\Models\ResumeSend', 'job_id', 'id')
            ->where('status', 5)
            ->count();
    }
}
